package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author 24040
 * @name OrderServiceImpl
 * @date 2022-08-01 11:51
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderService orderService;

    /**
     * 用户下单
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(qw);

        if(shoppingCarts == null || shoppingCarts.size() == 0){
            //如果购物车数据为空，这抛出异常
            throw new CustomException("购物车为空,不能下单");
        }
        //查询用户数据
        User user = userService.getById(userId);

        //查询地址数据
        Long addressBookId = orders.getAddressBookId();//地址的主键值
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null ){
            //如果地址为空，抛出异常
            throw new CustomException("地址信息有误，不能下单");
        }

        //向订单表插入数据，一条数据
        long orderId = IdWorker.getId();//订单号
        AtomicInteger amount = new AtomicInteger(0);//原子整数类保证线程安全，总金额

        //这里的装换成list集合是 为了方便之后封装订单明细
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item)->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(item.getName());//套餐/菜品id
            orderDetail.setImage(item.getImage());//图片
            orderDetail.setOrderId(orderId);//设置订单号
            orderDetail.setDishId(item.getDishId());//菜品id
            orderDetail.setSetmealId(item.getSetmealId());//套餐id
            orderDetail.setDishFlavor(item.getDishFlavor());//口味
            orderDetail.setNumber(item.getNumber());//数量
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            //单份的金额*份数 => 转成value
            return orderDetail;
        }).collect(Collectors.toList());


        orders.setCheckoutTime(LocalDateTime.now());
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(2);//设置订单状态
        orders.setNumber(String.valueOf(orderId));//设置订单号
        orders.setAmount(new BigDecimal(amount.get()));//设置总金额，需要单独处理
        orders.setUserId(userId);//用户id
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(user.getPhone());//手机号
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//设置地址
        this.save(orders);

        //向订单明细插入数据
        orderDetailService.saveBatch(orderDetails);
        //清空购物车数据
        shoppingCartService.remove(qw);
    }

    /**
     * 再来一单
     * @param ordersId
     * @param userId
     */
    @Override
    @Transactional
    public boolean again(Long ordersId,Long userId) {
        //1.清除当前用户的购物车信息
        LambdaQueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new LambdaQueryWrapper<ShoppingCart>();
        shoppingCartQueryWrapper.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(shoppingCartQueryWrapper);

        //根据订单id，查询订单号
        Orders orderServiceById = orderService.getById(ordersId);
        String number = orderServiceById.getNumber();//订单号


        //2.获取当前订单详情信息（根据订单号），为一个list集合
        LambdaQueryWrapper<OrderDetail> orderDetailQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailQueryWrapper.eq(OrderDetail::getOrderId,Long.valueOf(number));
        List<OrderDetail> list = orderDetailService.list(orderDetailQueryWrapper);


        //3.遍历当前list集合，把详细订单中的信息赋给shoppingCarts，并设置shoppingCart的属性
        List<ShoppingCart> shoppingCarts = list.stream().map((item)->{
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item,shoppingCart,
                        "id","orderId");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());


        //4.保存该集合
        boolean b = shoppingCartService.saveBatch(shoppingCarts);
        return b;
    }
}
